<template>
  <div class="app-container">
    <!-- 顶部控制台 -->
    <div class="filter-container" style="text-align: left">
      <el-input class="filter-item" style="width: 160px" v-model="form.searchTitle" size="mini" placeholder="请输入搜索的题库标题"/>
      <el-button type="primary" icon="el-icon-search" @click="handlePageInit" size="mini">搜索</el-button>
      <el-button type="primary" icon="el-icon-search" @click="handleOpenSavePage" size="mini">新建题库</el-button>
    </div>
    <!-- 页面数据列表 -->
    <el-table :data="responseData.tableList"
              border style="width: 100%;"
              v-loading="pageData.loading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              :header-cell-style="{ background: '#545C64', color: '#ffffff' }"
              @selection-change="handleTableSelection">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column fixed="left" prop="id" label="题库ID" width="270" align="center"/>
      <el-table-column prop="name" label="题库名称" width="320" align="center"/>
      <el-table-column prop="showIndex" label="展示顺序" width="320" align="center"/>
      <el-table-column prop="count" label="题目数量" width="320" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleJumpQuestionPage(scope)">{{ scope.row.count }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" :formatter="handleFormatTableDateColumn"/>
      <el-table-column prop="updateTime" label="更新时间" width="180" align="center" :formatter="handleFormatTableDateColumn"/>
      <el-table-column fixed="right" label="操作" width="240" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleOpenEditPage(scope)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteData(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="form.pageNum"
      :page-size="form.pageSize"
      :total="form.total"
      :page-sizes="[12, 50, 100, 200]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>
    <!-- 新增/修改隐藏域 -->
    <el-dialog :title="pageData.savePanelTitle" :visible.sync="pageData.savePanelStatus" size="tiny" width="480px"
               :before-close="handleCloseSavePanel">
      <el-form :model="form" label-width="80px" ref="form">
        <el-form-item prop="name" label="题库名称">
          <el-input placeholder="请输入题库名称" v-model="form.name" class="filter-item" auto-complete="off"/>
        </el-form-item>
        <el-form-item prop="showIndex" label="展示顺序">
          <el-input placeholder="请输入题库名称" v-model="form.showIndex" type="number" class="filter-item" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="small" style="margin-top: 30px" @click="handleSaveButtonClick">保存数据</el-button>
    </el-dialog>
  </div>
</template>

<script>
  // 组件引入
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';
  // 接口引入
  import { loadCmsExamQuestionWarehouseList,saveCmsExamQuestionWarehouseData,updateCmsExamQuestionWarehouseData,deleteCmsExamQuestionWarehouseData } from "@/api/study";
  export default {
    name: "question",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        pageData:{
          loading: false,
          savePanelTitle: "",
          savePanelStatus: false,
          savePanelType: 0
        },// 页面配置数据
        form:{
          searchTitle: "",
          id: 0,
          name: "",
          showIndex: 0,
          pageNum: 1,// 表单--页码
          pageSize: 12,// 表单--页面
          total: 0,// 表单--总量
          selection: []// 多选的内容
        },// 页面表单
        formRules: {},// 表单验证
        responseData: {
          tableList: []
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods:{
      // 方法函数
      handlePageInit(){
        this.form.pageNum = 1;
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionWarehouseList();
      },// 页面初始化事件
      handleCurrentChange(val){
        this.form.pageNum = val;// 更换页码
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionWarehouseList();
      },// 页码切换事件
      handleSizeChange(val){
        this.form.pageSize = val;// 更换页面大小
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionWarehouseList();
      },// 页面size切换事件
      handleTableSelection(val){
        let list = [];// 初始化多选数组
        for (let i=0; i<val.length; i++){
          list.push(val[i].id);
        }// 遍历多选的列表，将ID拼入数组中
        this.form.selection = list;// 进行多选值的切换
      },// 表格多选事件
      handleOpenSavePage(){
        if (PermissionsToDetectFormUser(getPermission(), "730001")){
          // 打开面板
          this.form.id = 0;
          this.form.name = "";
          this.form.showIndex = 0;
          this.pageData.savePanelTitle = "题库新增";
          this.pageData.savePanelStatus = true;
          this.pageData.savePanelType = 1;
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开题库新增面板
      handleCloseSavePanel(){
        this.$confirm("确认关闭？").then(response => {
          // 打开面板
          this.form.id = 0;
          this.form.name = "";
          this.form.showIndex = 0;
          this.pageData.savePanelTitle = "";
          this.pageData.savePanelStatus = false;
          this.pageData.savePanelType = 0;
        }).catch(err => {
          console.log(err);
        });
      },// 关闭面板提示
      handleOpenEditPage(scope){
        if (PermissionsToDetectFormUser(getPermission(), "730003")){
          this.form.id = scope.row.id;
          this.form.name = scope.row.name;
          this.form.showIndex = scope.row.showIndex;
          this.pageData.savePanelTitle = "题库修改";
          this.pageData.savePanelStatus = true;
          this.pageData.savePanelType = 2;
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开修改面板
      handleSaveButtonClick(){
        if (this.pageData.savePanelType === 1){
          if (!PermissionsToDetectFormUser(getPermission(), "730001")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
            return;
          }
        }
        if (this.pageData.savePanelType === 2){
          if (!PermissionsToDetectFormUser(getPermission(), "730003")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
            return;
          }
        }
        this.$confirm('是否保存当前题库, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.pageData.savePanelType === 1){
            this.saveCmsExamQuestionWarehouseData();
          } else if (this.pageData.savePanelType === 2){
            this.updateCmsExamQuestionWarehouseData();
          }
        }).catch(cancel => {
          console.log(cancel);
          this.$message.info("已取消操作");
        });
      },// 保存题库数据
      handleDeleteData(scope){
        if (PermissionsToDetectFormUser(getPermission(), "730002")){
          if (scope.row.count >= 1){
            this.$message.warning("当前题库下已有题目，不可进行删除，如需删除，请前往题目管理进行题目迁库");
          } else {
            // 当前操作权限充足，进行敏感操作提示
            this.$confirm('此操作将会删除当前数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 同一操作，执行具体流程
              let param = {
                id: scope.row.id
              };
              this.deleteCmsExamQuestionWarehouseData(param);
            }).catch(close => {
              console.log(close);
              this.$message.info('已取消操作');
            });
          }
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 删除题库按钮点击事件
      handleJumpQuestionPage(scope){
        localStorage.setItem('searchWarehouse',scope.row.id);// 将参数封装到缓存中
        let routeUrl = this.$router.resolve({path: "/study/question"});
        window.open(routeUrl.href, '_blank');// 使用开启新窗口跳转
      },// 跳转到题目列表页
      handleFormatTableDateColumn(row, column){
        let data = row[column.property];
        if (data ===null) {
          return ''
        }
        let dt = new Date(data);
        return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
      },// 时间字段格式化
      // 接口
      loadCmsExamQuestionWarehouseList(){
        loadCmsExamQuestionWarehouseList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            this.responseData.tableList = response.data.list;
            this.form.total = response.data.total;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取数据列表
      saveCmsExamQuestionWarehouseData(){
        saveCmsExamQuestionWarehouseData(this.form).then(response =>{
          if (response.code === "200"){
            this.$message.success("题库新建完成");
            // 打开面板
            this.form.id = 0;
            this.form.name = "";
            this.pageData.savePanelTitle = "";
            this.pageData.savePanelStatus = false;
            this.pageData.savePanelType = 0;
            this.handlePageInit();
          } else {
            console.log(response.message);
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 保存题库数据
      updateCmsExamQuestionWarehouseData(){
        updateCmsExamQuestionWarehouseData(this.form).then(response =>{
          if (response.code === "200"){
            this.$message.success("题库更新完成");
            // 打开面板
            this.form.id = 0;
            this.form.name = "";
            this.pageData.savePanelTitle = "";
            this.pageData.savePanelStatus = false;
            this.pageData.savePanelType = 0;
            this.handlePageInit();
          } else {
            console.log(response.message);
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 更新题库数据
      deleteCmsExamQuestionWarehouseData(param){
        deleteCmsExamQuestionWarehouseData(param).then(response => {
          if (response.code === "200"){
            // 初始化数据
            this.$message.success("删除成功");
            this.handlePageInit()
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 删除题库数据
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function () {
      let _this = this;
      // 进行初始化数据读取
      setTimeout(function () {
        document.onkeydown = function(e) {
          if (!_this.pageData.loading) {
            let key = window.event.keyCode;
            if (key === 13) {
              _this.handlePageInit(); //此方法是当按下enter键后要做的动作。
            }
          }
        };
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
